package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.domain.BusinessParams;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TPayChannel;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.business.service.ITPayChannelService;
import com.ruoyi.common.constant.GlobalConstants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.AesEncryptUtils;
import com.ruoyi.common.utils.MoneyUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service("gfalixcxPayService")
public class AliPayJsXcxServiceImpl extends BasePayment {

    @Resource
    private ISysDictDataService sysDictDataService;
    @Resource
    private ITPayChannelService payChannelService;

    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
       String payGateway =sysConfigService.selectConfigByKey("sys.bussine.payGateway");

        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
//        String qrcode = userRecipientInfo.getReceiptQrcode();
//        String qrcode_ = HttpUtils.getParam(qrcode,"userAppId");
        TPayChannel payChannel = payChannelService.selectTPayChannelByCode(orderInfo.getChannel());

        if(StringUtils.isBlank(orderInfo.getAliUserId())){
            Map map = new HashMap<>();
            map.put("c", orderInfo.getChannel());
            map.put("o", orderInfo.getId().toString());

            // 明文参数
            String p = JSONObject.toJSONString(map);
            // 密文参数
            String pp = AesEncryptUtils.encrypt(p);

            String url = payGateway + GlobalConstants.API_BASE_URL + "common/aliPayAuth/"+payChannel.getAliasName().toLowerCase()+"/" + pp;
            String aliUrl = "alipays://platformapi/startapp?appId=20000067&url=" + URLEncoder.encode(url);
//            String payUrl = "https://render.alipay.com/p/s/i?scheme=" + URLEncoder.encode(aliUrl);
            jsonObject.put("payUrl",aliUrl);
            jsonObject.put("orderNo","");
            jsonObject.put("code","200");
            return jsonObject;
        }
        JSONObject accountObj = JSONObject.parseObject(userRecipientInfo.getAccountJson());
        String alipayPublicKey = accountObj.getString("aliPublicKey");
        String alipayPrivateKey = accountObj.getString("aliPrivateKey");
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                userRecipientInfo.getChannelAccount(), alipayPrivateKey, "json", "UTF-8", alipayPublicKey, "RSA2");
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        AlipayTradeCreateModel model = new AlipayTradeCreateModel();

        // 设置商户门店编号
//        model.setStoreId("NJ_001");

        // 设置业务扩展参数
//        ExtendParams extendParams = new ExtendParams();
//        extendParams.setSysServiceProviderId("2088511833207846");
//        model.setExtendParams(extendParams);

        // 设置订单标题
//        model.setSubject("Iphone6 16G");
        SysDictData sysDictDataQuery = new SysDictData();
        sysDictDataQuery.setDictType("zft_subject");
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(sysDictDataQuery);
        Random random = new Random();
        int index = random.nextInt(sysDictDataList.size());
        SysDictData element = sysDictDataList.get(index);
        model.setSubject(element.getDictLabel());
        // 设置商户操作员编号
//        model.setOperatorId("yx_001");

        // 设置产品码
        model.setProductCode("JSAPI_PAY");
        model.setOpAppId("2021005142623022");
        model.setBuyerId(orderInfo.getAliUserId());

//        // 设置订单附加信息
//        model.setBody("Iphone6 16G");
//
//        // 设置订单包含的商品列表信息
//        List<GoodsDetail> goodsDetail = new ArrayList<GoodsDetail>();
//        GoodsDetail goodsDetail0 = new GoodsDetail();
//        goodsDetail0.setGoodsName("ipad");
//        goodsDetail0.setQuantity(1L);
//        goodsDetail0.setPrice("2000");
//        goodsDetail0.setGoodsId("apple-01");
//        goodsDetail0.setGoodsCategory("34543238");
//        goodsDetail0.setCategoriesTree("124868003|126232002|126252004");
//        goodsDetail0.setShowUrl("http://www.alipay.com/xxx.jpg");
//        goodsDetail.add(goodsDetail0);
//        model.setGoodsDetail(goodsDetail);
//
//        // 设置商户的原始订单号
//        model.setMerchantOrderNo("20161008001");
//
//        // 设置可打折金额
//        model.setDiscountableAmount("80.00");

        // 设置商户订单号
        model.setOutTradeNo(orderInfo.getId()+"");

        // 设置订单总金额
        model.setTotalAmount(MoneyUtil.fenToYuan(orderInfo.getMoney()+""));

        // 设置商户传入业务信息
        BusinessParams businessParams = new BusinessParams();
        businessParams.setMcCreateTradeIp(orderInfo.getOutBody());
        model.setBusinessParams(businessParams);

//
//        // 设置卖家支付宝用户ID
//        model.setSellerId("2088102146225135");
//
//        // 设置商户机具终端编号
//        model.setTerminalId("NJ_T_001");

        request.setBizModel(model);
        request.setNotifyUrl(payGateway+"/notify/alipay/notifySucc");
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");
        logger.info("jsapi参数：{}",JSONObject.toJSONString(request));
        AlipayTradeCreateResponse response = alipayClient.execute(request);
        logger.info("jsapi返回：{}",response.getBody());
        jsonObject.put("payUrl","alipays://platformapi/startapp?appId=2021005142623022&page=/pages/index/index"+ URLEncoder.encode("?tradeNO="+response.getTradeNo()));
        jsonObject.put("orderNo",response.getTradeNo());
        jsonObject.put("code","200");
        return jsonObject;
    }

    public JSONObject createWxPayOrder(TOrderInfo orderInfo) throws ServiceException, UnsupportedEncodingException {
        return null;
    }

    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        return new ResponseData();
    }

}
